package com.example.service;

import com.example.common.Result;
import com.example.entity.DailyRecords;
import com.example.mapper.DailyRecordMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class DailyRecordService {
    @Resource
    private DailyRecordMapper dailyRecordMapper;

    public Result addDailyRecord(DailyRecords dailyRecords) {
        if(dailyRecords.getMoodOrEvent()==null){
            return Result.error();
        }
        // 获取当前日期的年月日部分
        LocalDate today = LocalDate.now();
        // 将LocalDate转换为Date对象（时间部分为00:00:00）
        Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
        dailyRecords.setRecordDate(date);
        if(dailyRecords.getMoodOrEvent().equals(1)){
            DailyRecords old = dailyRecordMapper.getByDateUserId(dailyRecords);
            if(old == null){
                dailyRecordMapper.add(dailyRecords);
            }else {
                dailyRecordMapper.updateMood(dailyRecords);
            }
        }
        if(dailyRecords.getMoodOrEvent().equals(2)){
            dailyRecordMapper.add(dailyRecords);
        }
        return Result.success("添加成功");
    }

    public Result updateDailyRecord(DailyRecords dailyRecords) {
        Date date = new Date();
        dailyRecords.setRecordDate(date);
        if(!dailyRecordMapper.updateEvent(dailyRecords)){
            return Result.error("更新失败");
        }
        return Result.success("更新成功");
    }

    public Result list(DailyRecords dailyRecords) {
        List<DailyRecords> dailyRecordsList = dailyRecordMapper.list(dailyRecords);
        return Result.success(dailyRecordsList);
    }

    public Result listAll(DailyRecords dailyRecords) {
        List<DailyRecords> dailyRecordsList = dailyRecordMapper.listAll(dailyRecords);
        return Result.success(dailyRecordsList);
    }
}
